// A Simple Incremental Parser
// to compile: g++ -I/path/to/your/boost incremental-parser.cpp

#include <iostream>
#include <string>
#include <fstream>

#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_stl.hpp>

namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
namespace phoenix = boost::phoenix;

typedef std::vector<int> IntVec;
typedef std::string::const_iterator forward_iterator_type;


// A simple grammar: a model is a list of integers ends with 0.
// The integers of one model can be on different lines.
template <typename Iterator>
struct MyGrammar : qi::grammar<Iterator, ascii::space_type >
{

  MyGrammar(IntVec& V_) : MyGrammar::base_type(model), V(V_)
  {
    sentinel = qi::char_('0');
    
    literal = qi::int_ - sentinel;

    // When got a number, push it into an output vector
    model = +literal[phoenix::push_back(phoenix::ref(V), qi::_1)] >> sentinel;
  }

  qi::rule<Iterator, ascii::space_type > sentinel;
  qi::rule<Iterator, int(), ascii::space_type > literal;
  qi::rule<Iterator, ascii::space_type > model;

  IntVec& V;
};


int 
main()
{
  std::ifstream inputfile("input.txt");

  if (inputfile.is_open())
    {
 
      std::string line;

      while (!inputfile.eof())
	{
	  bool complete = false;
	  IntVec V;
	  MyGrammar<forward_iterator_type> g(V);
	  
	  while (!complete && !inputfile.eof())
	    {
	      // Parsing line by line
	      getline(inputfile, line);
	      std::cout << "Processing: " << line << std::endl;
	      
	      forward_iterator_type beg = line.begin();
	      forward_iterator_type end = line.end();

	      complete = qi::phrase_parse(beg, end, g, ascii::space);
	      if (complete)
		{
		  std::cout << "Parsing SUCCEEDED!" << std::endl;
		}
	      else
		{
		  std::cout << "Parsing FAILED!" << std::endl;
		}

	      std::copy(V.begin(), V.end(), 
			std::ostream_iterator<int>(std::cout, " "));
	      std::cout << std::endl;

	    }
	}
    }
  else
    {
      std::cout << "Unable to open input.txt" << std::endl;
    }
}
